package com.rd.student.jiaji.class2.duyukun.Day0724;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class TestSemaphore {

    private static Semaphore semaphore = new Semaphore(20);
    public static void main(String[] args) {
        for (int i = 0; i < 50; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()
                            + "来到停车场");
                    //返回可用车位数
                    if (semaphore.availablePermits() == 0){
                        System.out.println("车位不足请等待");
                    }
                    try{
                        //获取车位
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName()
                                + "请进入停车场");
                        Thread.sleep(new Random().nextInt(8888));

                        System.out.println(Thread.currentThread().getName()
                                + "开出停车场");
                        semaphore.release();

                    }catch (InterruptedException e){

                        throw new RuntimeException(e);
                    }

                }
            });
            thread.start();
        }
    }
}
